I'm guessing the problem is about it being async, and it tries to read it before the data is fetched, but that shouldn't happen. This code is same as on every tutorial. I thought useEffect and .then() are handling this. What's the problem here ? Actually on tutorials they access the data with categories.title directly, without even using categories[0]. I'm confused.
import React, { useState, useEffect } from "react";
import { useOutletContext } from "react-router-dom";
import Birimler from "../../components/birimler";
import sanityClient from "../../Client";
const Yasambilim = () => {
const { setTitle } = useOutletContext();
useState(() => {
setTitle("YAŞAMBİLİM");
}, []);
const [categories, setCategories] = useState([]);
useEffect(() => {
sanityClient
.fetch(
`*[_type == "article"]{
title,
slug,
}`
)
.then((data) => setCategories(data))
.catch(console.error);
}, []);
console.log(categories); /* prints [{…}] */
console.log(categories[0]); /* prints {slug: {…}, title: 'Test Title'} */
console.log(
categories[0].title
); /* app crashes Cannot read properties of undefined (reading 'title') */
return (
<>
<Birimler />
</>
);
};
export default Yasambilim;